package logic

import (
	"automated-modeling/models/cache"
	"automated-modeling/models/mysql"
	"automated-modeling/pkg"
	"context"
	"fmt"

	"automated-modeling/automatedrpc/automatedrpc"
	"automated-modeling/automatedrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *automatedrpc.UserLoginRequest) (*automatedrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("验证码输入错误,请重新输入")
	}

	var user mysql.Users
	mysql.DB.Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请先注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码不正确，请重新输入")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)

	return &automatedrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
